﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using PNProject.Core;
using PNProject.Core.Converter;
using PNProject.Models;
using PNProject.EF;

namespace PNProject.Controllers
{
    public class AdminPSController : Controller
    {
        //
        // GET: /AdminPS/

        public ActionResult Index()
        {
            var list = StaticData.cateRepo.GetAll();
            return View(list);
        }

        public ActionResult Category(string id)
        {
            try
            {
                int newid = int.Parse(id);
                var list = StaticData.proRepo.GetSome(a => a.CategoryID == newid).ToList();
                if(list==null)
                    RedirectToAction("error","home");
                var dbo = StaticData.cateRepo.GetOne(a => a.CategoryID == newid);
                ViewData["head"] = dbo.CategoryName;
                ViewData["tlink"] = dbo.TLink;
                return View(list);
            }
            catch (Exception e)
            {
                return RedirectToAction("error", "home");
            }
        }

        public ActionResult Create(string id)
        {
            var dbo = StaticData.cateRepo.GetOne(a => a.TLink == id);
            if (dbo == null)
                return RedirectToAction("Error", "Home");
            return View(new Product() { CategoryID = dbo.CategoryID });
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(Product model, HttpPostedFileBase file, HttpPostedFileBase attach)
        {
            model.TLink = PNLibraries.PNChuyenKhongDau(model.Name);
            model.CreateDate = DateTime.Now;
            model.ProductID = Guid.NewGuid();
            model.ViewCount = 0;
            model.IsChecked = false;
            model.LastUpdate = DateTime.Now;
            if (string.IsNullOrEmpty(model.Avatar))
            {
                if (file != null)
                {
                    var legal = file.ContentType == "image/jpeg" || file.ContentType == "image/png" || file.ContentType == "image/gif" || file.ContentType == "image/jpg";
                    if (legal)
                    {
                        string time = PNLibraries.PNConvertToTimestamp(DateTime.Now).ToString();
                        string newName = time + "-" + file.FileName;
                        string path = "/Application_Data/Images/ProductImages/";
                        ServerHelper.SaveFileBaseOnServer(path, file, newName);
                        model.Avatar = path + newName;
                    }
                }
            }
            else
            {
                model.Avatar = model.Avatar;
            }
            if (attach != null)
            {
                var legal = attach.ContentType == "image/jpeg" || attach.ContentType == "image/png" || attach.ContentType == "image/gif" || attach.ContentType == "image/jpg";
                if (legal)
                {
                    string time = PNLibraries.PNConvertToTimestamp(DateTime.Now).ToString();
                    string newName = time + "-" + attach.FileName;
                    string path = "/Application_Data/Images/ProductImages/";
                    ServerHelper.SaveFileBaseOnServer(path, file, newName);
                    model.Images = path + newName + "*$*";
                }
            }
            StaticData.proRepo.Save(null, model);
            return RedirectToAction("Category", new { id = model.CategoryID.ToString() });
        }

        public ActionResult Edit(string id)
        {
            Guid newid = Guid.NewGuid();
            try{
                newid = Guid.Parse(id);
            }catch(Exception e){
            }

            
            var dbo = StaticData.proRepo.GetOne(a => a.ProductID == newid);
            if (dbo == null)
                return RedirectToAction("error", "home");
            string sid = dbo.ProductID.ToString();
            var cms = StaticData.commentRepo.GetSome(a => a.TargetID == sid).OrderByDescending(a => a.SentDate).ToList();
            if (cms != null)
                ViewData["cms"] = cms;
            else
                ViewData["cms"] = new List<Comment>();
            return View(dbo);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(Product model, HttpPostedFileBase file, HttpPostedFileBase attach)
        {
            var dbo = StaticData.proRepo.GetOne(a => a.ProductID == model.ProductID);
            if (dbo == null)
            {
                return RedirectToAction("Error", "Admin");
            }
            model.ViewCount = dbo.ViewCount;
            model.CreateDate = dbo.CreateDate;
            model.IsChecked = dbo.IsChecked;
            model.TLink = PNLibraries.PNChuyenKhongDau(model.Name);
            model.LastUpdate = DateTime.Now;
            
            if (string.IsNullOrEmpty(model.Avatar))
            {
                if (file != null)
                {
                    var legal = file.ContentType == "image/jpeg" || file.ContentType == "image/png" || file.ContentType == "image/gif" || file.ContentType == "image/jpg";
                    if (legal)
                    {
                        ServerHelper.DeleteFileOnServer(dbo.Avatar);
                        string time = PNLibraries.PNConvertToTimestamp(DateTime.Now).ToString();
                        string newName = time + "-" + file.FileName;
                        string path = "/Application_Data/Images/ProductImages/";
                        ServerHelper.SaveFileBaseOnServer(path, file, newName);
                        model.Avatar = path + newName;
                    }
                }
                else
                {
                    model.Avatar = "";
                    ServerHelper.DeleteFileOnServer(dbo.Avatar);
                }
            }
            else
            {
                if (dbo.Avatar != model.Avatar)
                    ServerHelper.DeleteFileOnServer(dbo.Avatar);
            }
            var removeset = ServerHelper.NotExistFileName(ServerHelper.SplitFileName(dbo.Images), ServerHelper.SplitFileName(model.Images));
            foreach (var item in removeset)
            {
                ServerHelper.DeleteFileOnServer(item);
            }
            if (attach != null)
            {
                string time = "pnco-" + PNLibraries.PNConvertToTimestamp(DateTime.Now).ToString();
                string newName = time + "-" + attach.FileName;
                string path = "/Application_Data/Images/ProductImages/";
                ServerHelper.SaveFileBaseOnServer(path, attach, newName);
                model.Images = model.Images + path + newName + "*$*";
            }
            StaticData.proRepo.Save(dbo, model);
            return RedirectToAction("Category", new { id = model.CategoryID.ToString() });
        }

        public ActionResult ContextMenu(string id)
        {
            Guid pid = Guid.NewGuid();
            try{
                pid = Guid.Parse(id);
            }
            catch(Exception e){}
            var dbo = StaticData.proRepo.GetOne(a => a.ProductID == pid);
            if (dbo == null)
                return RedirectToAction("Error", "admin");
            var list = StaticData.cmenuRepo.GetSome(a => a.ProductID == pid);
            ViewData["name"] = dbo.Name;
            ViewData["Pid"] = dbo.ProductID.ToString();
            return View(list);
        }

        public ActionResult CreateContext(string id)
        {
            Guid pid = Guid.NewGuid();
            try
            {
                pid = Guid.Parse(id);
            }
            catch (Exception e) { }
            var dbo = StaticData.proRepo.GetOne(a => a.ProductID == pid);
            if (dbo == null)
                return RedirectToAction("Error", "admin");
            ViewData["spn"] = dbo.Name;
            return View(new CMenu() { ProductID = pid });
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateContext(CMenu model)
        {
            model.CMenuID = Guid.NewGuid();
            model.LastUpdate = DateTime.Now;
            StaticData.cmenuRepo.Save(null, model);
            return RedirectToAction("ContextMenu", new { id = model.ProductID.ToString() });
        }

        public ActionResult EditContext(string id)
        {
            Guid pid = Guid.NewGuid();
            try
            {
                pid = Guid.Parse(id);
            }
            catch (Exception e) { }
            var cdbo = StaticData.cmenuRepo.GetOne(a => a.CMenuID == pid);
            if(cdbo==null)
                return RedirectToAction("Error", "admin");
            var pdo = StaticData.proRepo.GetOne(a => a.ProductID == cdbo.ProductID);
            if(pdo==null)
                return RedirectToAction("Error", "admin");
            ViewData["pname"] = pdo.Name;
            return View(cdbo);

        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditContext(CMenu model)
        {
            var dbo = StaticData.cmenuRepo.GetOne(a => a.CMenuID == model.CMenuID);
            if(dbo==null)
                return RedirectToAction("Error", "admin");
            model.LastUpdate = DateTime.Now;
            StaticData.cmenuRepo.Save(dbo, model);
            return RedirectToAction("ContextMenu", new { id = dbo.ProductID.ToString() });
        }

        public ActionResult DeleteContext(string id)
        {
            Guid pid = Guid.NewGuid();
            try
            {
                pid = Guid.Parse(id);
            }
            catch (Exception e) { }
            var cdbo = StaticData.cmenuRepo.GetOne(a => a.CMenuID == pid);
            if (cdbo == null)
                return RedirectToAction("Error", "admin");
            StaticData.cmenuRepo.Delete(cdbo);
            return RedirectToAction("ContextMenu", new { id = cdbo.ProductID.ToString() });
        }


        public ActionResult Delete(string id)
        {
            Guid pid = Guid.NewGuid();
            try
            {
                pid = Guid.Parse(id);
            }
            catch (Exception e) { }
            var dbo = StaticData.proRepo.GetOne(a => a.ProductID == pid);
            if (dbo == null)
                return RedirectToAction("Error", "admin");

            var list = StaticData.cmenuRepo.GetSome(a => a.ProductID == pid);
            foreach (var item in list)
            {
                StaticData.cmenuRepo.Delete(item);
            }
            StaticData.proRepo.Delete(dbo);
            return RedirectToAction("Category", new { id = dbo.CategoryID.ToString() });
        }

        public ActionResult ViewComment(string id)
        {
            try
            {
                Guid newid = Guid.Parse(id);
                var cm = StaticData.commentRepo.GetOne(a => a.CommentID == newid);
                if (cm != null)
                {
                    Guid pid = Guid.Parse(cm.TargetID);
                    var pr = StaticData.proRepo.GetOne(a => a.ProductID == pid);
                    ViewData["pr"] = pr.Name;
                    ViewData["cm"] = cm;
                }
                else
                    ViewData["cm"] = new Comment();
                return View();
            }
            catch(Exception e)
            {
                return RedirectToAction("Error","Admin");
            }
            
        }

        public ActionResult DeleteComment(string id)
        {
            try
            {
                Guid cid = Guid.Parse(id);
                var cm = StaticData.commentRepo.GetOne(a => a.CommentID == cid);
                StaticData.commentRepo.Delete(cm);
                return RedirectToAction("Edit", new { id = cm.TargetID });
            }
            catch (Exception e)
            {
                return RedirectToAction("error", "admin");
            }
        }


    }
}
